<template>
  <div class="dialog-container">
    <!-- AI自动创建任务 -->
    <div v-if="currentMode === 'ai'" class="ai-panel">
      <div class="panel-header">
        <div class="header-info">
          <Icon icon="ep:info-filled" class="info-icon" />
          <el-text class="info-text">输入要创建的任务即可自动创建外呼任务</el-text>
        </div>
        <el-button class="clear-btn" link @click="clearConversation">
          <Icon icon="ep:delete" />
          清空
        </el-button>
      </div>

      <div class="chat-container">
        <div class="chat-messages" ref="messagesContainer">
          <div
            v-for="(message, index) in currentMessages"
            :key="index"
            class="message"
            :class="message.role"
          >
            <div class="message-wrapper" :class="message.role">
              <el-avatar
                :size="32"
                class="message-avatar"
                :src="AiImg"
                v-if="message.role == 'ai'"
              />
              <div class="message-content" :class="message.role">
                <div class="message-text">
                  <!-- 如果是思考过程消息，特殊处理 -->
                  <div v-if="message.isThinking" class="thinking-process">
                    <div class="thinking-header">
                      <Icon icon="ep:loading" class="thinking-icon" />
                      <span class="thinking-title">AI正在思考创建任务...</span>
                    </div>
                    <div class="thinking-steps">
                      <div
                        v-for="(step, stepIndex) in message.steps"
                        :key="stepIndex"
                        class="thinking-step"
                        :class="{
                          'step-executing': step.status === 'executing',
                          'step-completed': step.status === 'completed'
                        }"
                      >
                        <div class="step-number" v-html="step.displayNumber + '.'"></div>
                        <div class="step-content">
                          <div class="step-text" v-html="step.text"></div>
                          <div v-if="step.status === 'executing'" class="step-loading">
                            <div class="loading-dots">
                              <span></span><span></span><span></span>
                            </div>
                          </div>
                          <div v-else-if="step.status === 'completed'" class="step-result">
                            <Icon icon="ep:check" class="check-icon" />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- 普通消息 -->
                  <span v-else v-html="message.content"></span>
                </div>
                <div class="message-time">{{ formatTime(new Date()) }}</div>
              </div>
              <el-avatar
                class="message-avatar"
                :size="32"
                :src="WoImg"
                v-if="message.role == 'user'"
              />
            </div>
          </div>

          <div v-if="isLoading && !hasThinkingMessage" class="message ai">
            <div class="message-wrapper ai">
              <el-avatar :size="32" class="message-avatar" :src="AiImg" />
              <div class="message-content ai">
                <div class="loading-container">
                  <span class="loading-text">AI正在思考</span>
                  <div class="loading-dots"> <span></span><span></span><span></span> </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input-container">
          <div class="input-wrapper">
            <el-input
              v-model="userInput"
              placeholder="请详细描述您要创建的外呼任务..."
              :disabled="isLoading"
              @keyup.enter="sendMessage"
              type="textarea"
              :rows="3"
              resize="none"
              class="chat-textarea"
            />
            <div class="input-actions">
              <div class="input-tip">
                <el-text size="small" type="info">Enter 发送</el-text>
              </div>
              <el-button
                type="primary"
                class="send-button ai-send"
                :disabled="isLoading || !userInput.trim()"
                @click="sendMessage"
                :loading="isLoading"
              >
                <Icon icon="ep:promotion" />
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 手动创建任务 -->
    <div v-if="currentMode === 'manual'" class="manual-panel">
      <div class="panel-header">
        <div class="header-info">
          <Icon icon="ep:edit-pen" class="info-icon" />
          <el-text class="info-text">手动创建外呼任务，支持自定义配置</el-text>
        </div>
        <el-button class="clear-btn" link @click="clearConversation">
          <Icon icon="ep:delete" />
          清空
        </el-button>
      </div>

      <div class="chat-container">
        <div class="chat-messages" ref="messagesContainer">
          <div
            v-for="(message, index) in currentMessages"
            :key="index"
            class="message"
            :class="message.role"
          >
            <div class="message-wrapper" :class="message.role">
              <el-avatar
                :size="32"
                class="message-avatar"
                :src="AiImg"
                v-if="message.role == 'ai'"
              />
              <div class="message-content" :class="message.role">
                <div class="message-text">
                  <!-- 处理包含按钮的HTML内容 -->
                  <div
                    class="flex items-end"
                    v-html="processMessageContent(message.content, index)"
                  ></div>
                </div>
                <div class="message-time">{{ formatTime(new Date()) }}</div>
              </div>
              <el-avatar
                class="message-avatar"
                :size="32"
                :src="WoImg"
                v-if="message.role == 'user'"
              />
            </div>
          </div>

          <div class="empty-state" v-if="currentMessages.length == 0">
            <Icon icon="ep:document" class="empty-icon" />
            <p class="empty-text">开始手动创建任务</p>
            <p class="empty-subtext">详细描述您的外呼任务需求</p>
          </div>

          <div v-if="isLoading" class="message ai">
            <div class="message-wrapper ai">
              <el-avatar :size="32" class="message-avatar" :src="AiImg" />
              <div class="message-content ai">
                <div class="loading-container">
                  <span class="loading-text">正在处理任务</span>
                  <div class="loading-dots"> <span></span><span></span><span></span> </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input-container">
          <div class="input-wrapper">
            <el-input
              v-model="userInput"
              placeholder="请详细描述您要手动创建的外呼任务..."
              :disabled="isLoading"
              @keyup.enter="sendMessage"
              type="textarea"
              :rows="4"
              resize="none"
              class="chat-textarea"
            />
            <div class="input-actions">
              <div class="input-tip">
                <el-text size="small" type="info"> Enter 发送</el-text>
              </div>
              <el-button
                type="primary"
                class="send-button manual-send"
                :disabled="isLoading || !userInput.trim()"
                @click="sendMessage"
                :loading="isLoading"
              >
                <Icon icon="ep:promotion" />
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- ai智能体 签入第三方 -->
    <div v-if="currentMode === 'largeModel'" class="model-panel">
      <div class="panel-header" v-if="!modelUrl">
        <div class="header-info">
          <Icon icon="ep:cpu" class="info-icon" />
          <el-text class="info-text">AI大模型智能对话</el-text>
        </div>
        <el-button class="config-btn" link @click="showConfigDialog">
          <Icon icon="ep:setting" />
          配置
        </el-button>
      </div>

      <div class="chat-container h-100%">
        <!-- 如果已配置URL，显示iframe -->
        <div v-if="modelUrl" class="iframe-container h-100%">
          <iframe
            :src="modelUrl"
            style="width: 100%; height: 100%; border: none"
            frameborder="0"
            allow="microphone"
          >
          </iframe>
        </div>

        <!-- 如果未配置URL，显示配置提示 -->
        <div v-else class="empty-state">
          <Icon icon="ep:chat-dot-round" class="empty-icon" />
          <p class="empty-text">开始配置与AI智能体对话吧</p>
          <p class="empty-subtext">
            <el-button type="primary" @click="showConfigDialog">配置</el-button>
          </p>
        </div>
      </div>
    </div>
    <ConfigDialog ref="configDialogRef" @config-saved="handleConfigSaved" />
  </div>
</template>

<script setup>
import { getTenantId, getAccessToken } from '@/utils/auth'
import { generateUUID } from '@/utils'
import { emitter } from '@/utils/eventBus.ts'
import { updateAiMessage } from '@/db/index.js'
import ConfigDialog from './dialog_m.vue'

import WoImg from '@/assets/img/wo.png'
import AiImg from '@/assets/img/ai.png'

const props = defineProps({
  currentConversation: {
    type: Object,
    default: null
  }
})

// 核心状态
const currentMessages = ref([])
const currentMode = ref('ai')
const isLoading = ref(false)
const userInput = ref('')
const controller = ref(null)
const messagesContainer = ref(null)

// AI思考相关状态
const hasThinkingMessage = ref(false)
const currentThinkingMessage = ref(null)
const stepNumberMap = ref(new Map())

// 手动模式按钮状态
const clickedButtons = ref(new Set())

// 大模型相关状态
const modelUrl = ref('')
const configDialogRef = ref(null)

// 内存缓存 - 区分消息缓存和配置缓存
const conversationCache = new Map() // 存储消息
const configCache = new Map() // 存储大模型配置

const baseUrl = ref('https://mcp.jzsaas.com')

// 核心：监听对话变化并加载内容
watch(
  () => props.currentConversation,
  async (newConversation, oldConversation) => {
    console.log('=== DialogBox: 对话变化 ===', {
      old: oldConversation?.uuid,
      new: newConversation?.uuid
    })

    // 保存旧对话到缓存
    if (oldConversation) {
      if (oldConversation.type === 'largeModel') {
        // 保存大模型配置到配置缓存
        const config = { url: modelUrl.value }
        console.log('DialogBox: 保存旧大模型配置到缓存', oldConversation.uuid, config)
        configCache.set(oldConversation.uuid, config)
        await saveModelConfig(oldConversation.uuid, config)
      } else if (currentMessages.value.length > 0) {
        // 保存普通对话到消息缓存
        console.log('DialogBox: 保存旧对话到缓存', oldConversation.uuid, currentMessages.value)
        conversationCache.set(oldConversation.uuid, [...currentMessages.value])
        await saveToDatabase(oldConversation.uuid, currentMessages.value)
      }
    }

    // 加载新对话
    if (newConversation) {
      currentMode.value = newConversation.type
      await loadConversationContent(newConversation)
    } else {
      currentMessages.value = []
      modelUrl.value = ''
    }
  },
  { immediate: true }
)

// 加载对话内容
const loadConversationContent = async (conversation) => {
  try {
    console.log('DialogBox: 开始加载对话', conversation.uuid, conversation.type)

    // 重置状态
    hasThinkingMessage.value = false
    currentThinkingMessage.value = null
    stepNumberMap.value.clear()
    clickedButtons.value.clear()

    // 如果是大模型模式，加载URL配置
    if (conversation.type === 'largeModel') {
      await loadModelConfig(conversation)
      return
    }

    // 其他模式的处理逻辑
    // 1. 优先从内存缓存加载
    if (conversationCache.has(conversation.uuid)) {
      const cachedMessages = conversationCache.get(conversation.uuid)
      console.log('DialogBox: 从缓存加载对话', conversation.uuid, cachedMessages)
      currentMessages.value = [...cachedMessages]
      await nextTick()
      scrollToBottom()
      return
    }

    // 2. 从数据库加载
    let messages = []
    if (
      conversation.content &&
      conversation.content.trim() !== '' &&
      conversation.content !== '[]'
    ) {
      try {
        const parsedContent = JSON.parse(conversation.content)
        if (Array.isArray(parsedContent) && parsedContent.length > 0) {
          messages = parsedContent
          console.log('DialogBox: 从数据库加载对话', conversation.uuid, messages)
        }
      } catch (e) {
        console.warn('DialogBox: 解析对话内容失败', e)
      }
    }

    currentMessages.value = messages

    // 缓存到内存
    if (messages.length > 0) {
      conversationCache.set(conversation.uuid, [...messages])
    }

    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('DialogBox: 加载对话失败', error)
    currentMessages.value = []
  }
}

// 加载大模型配置
const loadModelConfig = async (conversation) => {
  try {
    modelUrl.value = '' // 先清空

    // 1. 优先从配置缓存加载
    if (configCache.has(conversation.uuid)) {
      const cachedConfig = configCache.get(conversation.uuid)
      console.log('DialogBox: 从配置缓存加载', conversation.uuid, cachedConfig)
      modelUrl.value = cachedConfig.url || ''
      return
    }

    // 2. 从数据库加载
    if (conversation.content && conversation.content.trim() !== '') {
      const parsedContent = JSON.parse(conversation.content)

      // 检查是否是URL配置对象格式
      if (parsedContent && typeof parsedContent === 'object' && parsedContent.url) {
        modelUrl.value = parsedContent.url
        // 缓存到配置缓存
        configCache.set(conversation.uuid, { url: parsedContent.url })
        console.log('DialogBox: 从数据库加载大模型URL配置', parsedContent.url)
      }
      // 如果是旧的消息数组格式，清空并重置为空配置
      else if (Array.isArray(parsedContent)) {
        console.log('DialogBox: 检测到旧格式数据，重置为空配置')
        modelUrl.value = ''
        const emptyConfig = { url: '' }
        configCache.set(conversation.uuid, emptyConfig)
        await saveModelConfig(conversation.uuid, emptyConfig)
      }
    } else {
      console.log('DialogBox: 无配置数据，使用空URL')
      modelUrl.value = ''
      const emptyConfig = { url: '' }
      configCache.set(conversation.uuid, emptyConfig)
    }
  } catch (e) {
    console.warn('DialogBox: 解析大模型配置失败', e)
    modelUrl.value = ''
    const emptyConfig = { url: '' }
    configCache.set(conversation.uuid, emptyConfig)
    await saveModelConfig(conversation.uuid, emptyConfig)
  }
}

// 保存大模型配置的专用方法
const saveModelConfig = async (uuid, config) => {
  try {
    if (!uuid) return

    const content = JSON.stringify(config)
    console.log('DialogBox: 保存大模型配置', uuid, content)
    await updateAiMessage(uuid, content)

    // 更新配置缓存
    configCache.set(uuid, config)

    // 通知导航更新预览
    emitter.emit('updateConversationPreview', {
      uuid,
      messages: config,
      type: 'largeModel'
    })
  } catch (error) {
    console.error('DialogBox: 保存大模型配置失败', error)
    throw error
  }
}

// 显示配置对话框
const showConfigDialog = () => {
  if (props.currentConversation) {
    configDialogRef.value.open(props.currentConversation)
  }
}

// 处理配置保存
const handleConfigSaved = async (config) => {
  if (props.currentConversation) {
    modelUrl.value = config.url
    // 立即保存到缓存和数据库
    await saveModelConfig(props.currentConversation.uuid, config)
    console.log('DialogBox: 大模型配置已保存', config)
  }
}

// 实时保存到缓存和数据库
const saveConversation = async () => {
  if (!props.currentConversation) return

  if (props.currentConversation.type === 'largeModel') {
    // 大模型类型保存配置
    const config = { url: modelUrl.value }
    configCache.set(props.currentConversation.uuid, config)
    await saveModelConfig(props.currentConversation.uuid, config)
  } else {
    // 其他类型保存消息
    conversationCache.set(props.currentConversation.uuid, [...currentMessages.value])
    await saveToDatabase(props.currentConversation.uuid, currentMessages.value)
  }
}

// 修改通用保存方法
const saveToDatabase = async (uuid, data) => {
  try {
    if (!uuid || !data) return

    const content = JSON.stringify(data)
    console.log('DialogBox: 保存到数据库', uuid, content)
    await updateAiMessage(uuid, content)

    // 通知导航更新预览
    emitter.emit('updateConversationPreview', { uuid, messages: data })
  } catch (error) {
    console.error('DialogBox: 保存到数据库失败', error)
  }
}

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// AI模式相关方法
const processThinkingStep = (content, type) => {
  const stepMatch = content.match(/^(\d+)\.(.*)$/)
  if (!stepMatch) return null

  const originalStepNumber = parseInt(stepMatch[1])
  const stepText = stepMatch[2].trim()
  const status = type === 1 ? 'executing' : type === 2 ? 'completed' : 'normal'

  let displayNumber
  if (!stepNumberMap.value.has(originalStepNumber)) {
    displayNumber = stepNumberMap.value.size + 1
    stepNumberMap.value.set(originalStepNumber, displayNumber)
  } else {
    displayNumber = stepNumberMap.value.get(originalStepNumber)
  }

  return {
    originalNumber: originalStepNumber,
    text: stepText,
    status: status,
    displayNumber: displayNumber
  }
}

const updateThinkingMessage = (step) => {
  if (!currentThinkingMessage.value) {
    const thinkingMessage = {
      role: 'ai',
      content: '',
      isThinking: true,
      steps: []
    }
    currentMessages.value.push(thinkingMessage)
    currentThinkingMessage.value = thinkingMessage
    hasThinkingMessage.value = true
  }

  const thinkingMsg = currentThinkingMessage.value
  const existingStepIndex = thinkingMsg.steps.findIndex(
    (s) => s.originalNumber === step.originalNumber
  )

  if (existingStepIndex !== -1) {
    thinkingMsg.steps[existingStepIndex] = { ...thinkingMsg.steps[existingStepIndex], ...step }
  } else {
    thinkingMsg.steps.push(step)
    thinkingMsg.steps.sort((a, b) => a.displayNumber - b.displayNumber)
  }
}

const completeThinkingProcess = () => {
  if (currentThinkingMessage.value) {
    const allSteps = currentThinkingMessage.value.steps
      .sort((a, b) => a.displayNumber - b.displayNumber)
      .map((step) => {
        const statusText = step.status === 'completed' ? step.text : step.text
        return `${step.displayNumber}. ${statusText}`
      })
      .join('<br>')

    currentThinkingMessage.value.isThinking = false
    currentThinkingMessage.value.content = allSteps || '任务处理完成'

    hasThinkingMessage.value = false
    currentThinkingMessage.value = null
  }
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value || !props.currentConversation) return

  const userMessage = userInput.value.trim()
  const conversationUuid = props.currentConversation.uuid

  console.log('DialogBox: 发送消息', userMessage, '对话UUID:', conversationUuid)

  // 添加用户消息
  currentMessages.value.push({
    role: 'user',
    content: userMessage
  })

  // 立即保存
  await saveConversation()

  userInput.value = ''
  isLoading.value = true

  await nextTick()
  scrollToBottom()

  controller.value = new AbortController()

  try {
    let url

    if (currentMode.value === 'ai') {
      // AI模式 - 重置思考状态
      hasThinkingMessage.value = false
      currentThinkingMessage.value = null
      stepNumberMap.value.clear()
      url = baseUrl.value + '/admin-api/ai/manus/chat'
    } else {
      // 手动模式
      url = baseUrl.value + '/admin-api/ai/generateStreamAsString'
    }

    const response = await fetch(
      url + `?message=${encodeURIComponent(userMessage)}&chatId=${conversationUuid}`,
      {
        method: 'GET',
        headers: {
          Accept: '*',
          Authorization: 'Bearer ' + getAccessToken(),
          'tenant-id': getTenantId()
        },
        signal: controller.value.signal
      }
    )

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    let aiResponse = ''
    let aiMessageIndex = -1

    // 为AI响应创建消息
    if (currentMode.value === 'manual') {
      aiMessageIndex = currentMessages.value.length
      currentMessages.value.push({
        role: 'ai',
        content: ''
      })
    }

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      // 检查对话是否还是当前对话
      if (!props.currentConversation || props.currentConversation.uuid !== conversationUuid) {
        console.log('DialogBox: 对话已切换，停止处理响应')
        break
      }

      buffer += decoder.decode(value, { stream: true })

      let eventEnd
      while ((eventEnd = buffer.indexOf('\n\n')) !== -1) {
        const eventStr = buffer.substring(0, eventEnd).trim()
        buffer = buffer.substring(eventEnd + 2)

        if (!eventStr.startsWith('data:')) continue
        const dataStr = eventStr.replace('data:', '').trim()

        if (dataStr === '[complete]') {
          if (currentMode.value === 'ai') {
            completeThinkingProcess()
          }
          await saveConversation()
          continue
        }

        try {
          if (currentMode.value === 'ai') {
            // AI模式处理
            const data = JSON.parse(dataStr)
            if (data.content && data.content !== '[complete]') {
              const content = data.content.trim()
              const type = data.type || 3

              if (type === 1 || type === 2) {
                // 思考步骤
                const step = processThinkingStep(content, type)
                if (step) {
                  updateThinkingMessage(step)
                }
              } else {
                // 普通消息
                if (hasThinkingMessage.value) {
                  completeThinkingProcess()
                }
                currentMessages.value.push({
                  role: 'ai',
                  content: content
                })
              }
            }
          } else {
            // 手动模式处理
            if (dataStr && dataStr !== '[complete]') {
              aiResponse += dataStr
              if (aiMessageIndex !== -1) {
                currentMessages.value[aiMessageIndex].content = aiResponse
              }
            }
          }

          await saveConversation()
          await nextTick()
          scrollToBottom()
        } catch (e) {
          console.error('DialogBox: 解析数据失败', e)
        }
      }
    }
  } catch (error) {
    if (error.name !== 'AbortError') {
      console.error('DialogBox: 发送消息失败', error)
      currentMessages.value.push({
        role: 'system',
        content: `发生错误: ${error.message}`
      })
      await saveConversation()
    }
  } finally {
    isLoading.value = false
    controller.value = null
    if (currentMode.value === 'ai' && hasThinkingMessage.value) {
      completeThinkingProcess()
    }
    await nextTick()
    scrollToBottom()
  }
}

// 手动模式相关方法
const processMessageContent = (content, messageIndex) => {
  if (!content) return ''

  const buttonRegex = /<button[^>]*>(.*?)<\/button>/gi
  let buttonIndex = 0

  return content.replace(buttonRegex, (match, buttonText) => {
    const buttonId = `btn_${messageIndex}_${buttonIndex}`
    const isClicked = clickedButtons.value.has(buttonId)

    buttonIndex++

    if (isClicked) {
      return `<span class="clicked-button-placeholder">✅ ${buttonText.trim()}</span>`
    }

    return `
      <button 
        type="button"
        id="${buttonId}" 
        class="ai-action-button" 
        data-button-text="${buttonText.trim()}" 
        data-button-id="${buttonId}"
        onclick="window.handleAIButtonClick(this)"
      >
        <span class="button-icon">🚀</span>
        <span class="button-text">${buttonText.trim()}</span>
        <span class="button-arrow">→</span>
      </button>
    `
  })
}

const handleButtonClick = async (buttonText, buttonElement) => {
  if (isLoading.value) return

  const buttonId = buttonElement.getAttribute('data-button-id')
  if (buttonId) {
    clickedButtons.value.add(buttonId)
  }

  currentMessages.value.push({
    role: 'user',
    content: `✅ ${buttonText}`
  })

  // 实时保存
  await saveConversation()

  await nextTick()
  scrollToBottom()

  // 发送按钮消息
  await sendButtonMessage(buttonText)
}

const sendButtonMessage = async (buttonText) => {
  if (!props.currentConversation) return

  isLoading.value = true
  controller.value = new AbortController()
  const conversationUuid = props.currentConversation.uuid

  try {
    const aiMessageIndex = currentMessages.value.length
    currentMessages.value.push({
      role: 'ai',
      content: ''
    })

    const url = baseUrl.value + '/admin-api/ai/generateStreamAsString'
    const response = await fetch(
      url + `?message=${encodeURIComponent(buttonText)}&chatId=${conversationUuid}`,
      {
        method: 'GET',
        headers: {
          Accept: '*',
          Authorization: 'Bearer ' + getAccessToken(),
          'tenant-id': getTenantId()
        },
        signal: controller.value.signal
      }
    )

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    let aiResponse = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      // 检查对话是否还是当前对话
      if (!props.currentConversation || props.currentConversation.uuid !== conversationUuid) {
        console.log('DialogBox: 对话已切换，停止处理按钮响应')
        break
      }

      buffer += decoder.decode(value, { stream: true })

      let eventEnd
      while ((eventEnd = buffer.indexOf('\n\n')) !== -1) {
        const eventStr = buffer.substring(0, eventEnd).trim()
        buffer = buffer.substring(eventEnd + 2)

        if (!eventStr.startsWith('data:')) continue
        const dataStr = eventStr.replace('data:', '').trim()

        if (dataStr === '[complete]') {
          await saveConversation()
          continue
        }

        try {
          if (dataStr && dataStr !== '[complete]') {
            aiResponse += dataStr
            currentMessages.value[aiMessageIndex].content = aiResponse
            await saveConversation()
            await nextTick()
            scrollToBottom()
          }
        } catch (e) {
          console.error('DialogBox: 解析按钮响应失败', e)
        }
      }
    }
  } catch (error) {
    if (error.name !== 'AbortError') {
      console.error('DialogBox: 发送按钮消息失败', error)
      currentMessages.value.push({
        role: 'system',
        content: `发生错误: ${error.message}`
      })
      await saveConversation()
    }
  } finally {
    isLoading.value = false
    controller.value = null
    await nextTick()
    scrollToBottom()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 清空对话
const clearConversation = async () => {
  if (props.currentConversation) {
    if (props.currentConversation.type === 'largeModel') {
      // 清空大模型配置
      modelUrl.value = ''
      const emptyConfig = { url: '' }
      configCache.set(props.currentConversation.uuid, emptyConfig)
      await saveModelConfig(props.currentConversation.uuid, emptyConfig)
    } else {
      // 清空普通对话
      currentMessages.value = []
      hasThinkingMessage.value = false
      currentThinkingMessage.value = null
      stepNumberMap.value.clear()
      clickedButtons.value.clear()

      conversationCache.set(props.currentConversation.uuid, [])
      await saveToDatabase(props.currentConversation.uuid, [])
    }
  }
}

// 初始化
onMounted(() => {
  // 设置全局按钮点击处理函数
  window.handleAIButtonClick = (buttonElement) => {
    const buttonText = buttonElement.getAttribute('data-button-text')
    if (buttonText) {
      handleButtonClick(buttonText, buttonElement)
    }
  }
})

// 组件卸载时保存当前对话
onUnmounted(() => {
  if (controller.value) {
    controller.value.abort()
  }

  // 保存当前对话状态
  if (props.currentConversation) {
    if (props.currentConversation.type === 'largeModel') {
      const config = { url: modelUrl.value }
      configCache.set(props.currentConversation.uuid, config)
      saveModelConfig(props.currentConversation.uuid, config)
    } else if (currentMessages.value.length > 0) {
      conversationCache.set(props.currentConversation.uuid, [...currentMessages.value])
      saveToDatabase(props.currentConversation.uuid, currentMessages.value)
    }
  }

  // 清理全局函数
  if (window.handleAIButtonClick) {
    delete window.handleAIButtonClick
  }
})

// 暴露方法
defineExpose({
  clearConversation
})
</script>

<style scoped>
/* 保持原有样式 */
.dialog-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.ai-panel,
.manual-panel,
.model-panel {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #e8f4ff;
}
.ai-panel .panel-header {
  background: linear-gradient(135deg, #f8faff 0%, #f0f7ff 100%);
}

.manual-panel .panel-header {
  background: linear-gradient(135deg, #fff8f0 0%, #fff4e6 100%);
  border-color: #ffe7cc;
}
.model-panel .panel-header {
  background: linear-gradient(135deg, #f8faff 0%, #f4f5f7 100%);
}

.header-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ai-panel .info-icon {
  color: #0052cc;
  font-size: 16px;
}

.manual-panel .info-icon {
  color: #ff8c00;
  font-size: 16px;
}

.ai-panel .info-text {
  color: #0052cc;
  font-weight: 500;
}

.manual-panel .info-text {
  color: #d2691e;
  font-weight: 500;
}

.clear-btn {
  color: #666;
  transition: all 0.2s ease;
}

.ai-panel .clear-btn:hover {
  color: #0052cc;
}

.manual-panel .clear-btn:hover {
  color: #ff8c00;
}

.chat-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  background: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 82, 204, 0.08);
  border: 1px solid #e8f4ff;
}

.manual-panel .chat-container {
  box-shadow: 0 2px 12px rgba(255, 140, 0, 0.08);
  border-color: #ffe7cc;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: linear-gradient(180deg, #fafbff 0%, #f8faff 100%);
  scroll-behavior: smooth;
}

.manual-panel .chat-messages {
  background: linear-gradient(180deg, #fffbf7 0%, #fff8f0 100%);
}

.message {
  margin-bottom: 20px;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  max-width: 85%;
}

.message-wrapper.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-wrapper.ai {
  margin-right: auto;
}

.message-avatar {
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 82, 204, 0.15);
}

.message-content {
  position: relative;
  border-radius: 16px;
  padding: 12px 16px;
  word-break: break-word;
  white-space: pre-wrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.ai-panel .message-content.user {
  background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.manual-panel .message-content.user {
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.message-content.ai {
  background: #ffffff;
  color: #333;
  border: 1px solid #e8f4ff;
  border-bottom-left-radius: 4px;
}

.manual-panel .message-content.ai {
  border-color: #ffe7cc;
}

.message-text {
  line-height: 1.5;
  margin-bottom: 4px;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  text-align: right;
}

.message-content.ai .message-time {
  color: #999;
}

.message-content.user .message-time {
  color: rgba(255, 255, 255, 0.8);
}

/* 思考过程样式 */
.thinking-process {
  min-width: 300px;
}

.thinking-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e8f4ff;
}

.thinking-icon {
  color: #0052cc;
  font-size: 16px;
  animation: spin 2s linear infinite;
}

.thinking-title {
  font-weight: 500;
  color: #0052cc;
}

.thinking-steps {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.thinking-step {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 8px 12px;
  border-radius: 8px;
  background: #f8faff;
  border: 1px solid #e8f4ff;
  transition: all 0.3s ease;
}

.thinking-step.step-executing {
  background: linear-gradient(135deg, #fff4e6 0%, #ffe7cc 100%);
  border-color: #ffd4a3;
}

.thinking-step.step-completed {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-color: #bae6fd;
}

.step-number {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  background: #0052cc;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 500;
}

.step-executing .step-number {
  background: #ff8c00;
}

.step-completed .step-number {
  background: #10b981;
}

.step-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.step-text {
  flex: 1;
  font-size: 14px;
  line-height: 1.4;
}

.step-loading {
  margin-left: 12px;
}

.step-result {
  margin-left: 12px;
}

.check-icon {
  color: #10b981;
  font-size: 16px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  text-align: center;
}

.ai-panel .empty-icon {
  font-size: 48px;
  color: #0052cc;
  margin-bottom: 16px;
  opacity: 0.6;
}

.manual-panel .empty-icon {
  font-size: 48px;
  color: #ff8c00;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  color: #333;
  margin: 0 0 8px 0;
  font-weight: 500;
}

.empty-subtext {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.loading-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.loading-text {
  color: #666;
  font-size: 14px;
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  animation: loading-bounce 1.4s infinite;
  opacity: 0.3;
}

.ai-panel .loading-dots span {
  background: #0052cc;
}

.manual-panel .loading-dots span {
  background: #ff8c00;
}

.loading-dots span:nth-child(1) {
  animation-delay: 0s;
}

.loading-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.loading-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes loading-bounce {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.3;
  }
  40% {
    transform: scale(1.2);
    opacity: 1;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.chat-input-container {
  background: #ffffff;
  border-top: 1px solid #e8f4ff;
  padding: 16px 20px;
}

.manual-panel .chat-input-container {
  border-top-color: #ffe7cc;
}

.input-wrapper {
  position: relative;
}

.chat-textarea {
  margin-bottom: 12px;
}

.chat-textarea :deep(.el-textarea__inner) {
  border: 1px solid #e8f4ff;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  transition: all 0.2s ease;
}

.manual-panel .chat-textarea :deep(.el-textarea__inner) {
  border-color: #ffe7cc;
}

.ai-panel .chat-textarea :deep(.el-textarea__inner):focus {
  border-color: #0052cc;
  box-shadow: 0 0 0 2px rgba(0, 82, 204, 0.1);
}

.manual-panel .chat-textarea :deep(.el-textarea__inner):focus {
  border-color: #ff8c00;
  box-shadow: 0 0 0 2px rgba(255, 140, 0, 0.1);
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-tip {
  color: #999;
}

.send-button {
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.ai-send {
  background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
  box-shadow: 0 2px 8px rgba(0, 82, 204, 0.2);
}

.manual-send {
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  box-shadow: 0 2px 8px rgba(255, 140, 0, 0.2);
}

.send-button:hover {
  transform: translateY(-1px);
}

.ai-send:hover {
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
}

.manual-send:hover {
  box-shadow: 0 4px 12px rgba(255, 140, 0, 0.3);
}

.send-button:active {
  transform: translateY(0);
}

.send-button:disabled {
  background: #f5f7fa;
  color: #c0c4cc;
  transform: none;
  box-shadow: none;
}

/* AI按钮样式 */
:deep(.ai-action-button) {
  display: flex;
  align-items: center;
  padding: 17px;
  margin: 0;
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(255, 140, 0, 0.3);
  position: relative;
  overflow: hidden;
  width: 100px;
  flex-shrink: 0;
  height: 40px;
}

:deep(.ai-action-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 140, 0, 0.4);
  background: linear-gradient(135deg, #ffa500 0%, #ffb84d 100%);
}

:deep(.button-icon) {
  font-size: 16px;
  animation: pulse 2s infinite;
}

:deep(.button-text) {
  flex: 1;
  text-align: center;
}

:deep(.button-arrow) {
  font-size: 16px;
  font-weight: bold;
  transition: transform 0.3s ease;
}

:deep(.ai-action-button:hover .button-arrow) {
  transform: translateX(4px);
}

:deep(.clicked-button-placeholder) {
  display: none;
}

@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.ai-panel .chat-messages::-webkit-scrollbar-track {
  background: #f8faff;
  border-radius: 3px;
}

.manual-panel .chat-messages::-webkit-scrollbar-track {
  background: #fff8f0;
  border-radius: 3px;
}

.ai-panel .chat-messages::-webkit-scrollbar-thumb {
  background: rgba(0, 82, 204, 0.2);
  border-radius: 3px;
}

.manual-panel .chat-messages::-webkit-scrollbar-thumb {
  background: rgba(255, 140, 0, 0.2);
  border-radius: 3px;
}

.ai-panel .chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 82, 204, 0.3);
}

.manual-panel .chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 140, 0, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    height: 400px;
  }

  .message-wrapper {
    max-width: 95%;
  }

  .panel-header {
    padding: 12px 16px;
  }

  .chat-messages {
    padding: 16px;
  }

  .chat-input-container {
    padding: 12px 16px;
  }

  :deep(.ai-action-button) {
    padding: 10px 16px;
    font-size: 13px;
  }
}
</style>
